﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using VO.Business.Controllers;
using VO.Entities;

namespace VO.Web
{
    /// <summary>
    /// Summary description for UserLogo
    /// </summary>
    public class UserLogo : IHttpHandler, IReadOnlySessionState //IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //HttpContext.Current.
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            int userId = 0;
            Int32.TryParse(context.Request.QueryString["uid"], out userId);
            bool clearImage = context.Request.QueryString.AllKeys.Contains("clear");
            if (clearImage)
            {
                context.Response.WriteFile("images/user-unknow-icon-100.jpg");
            }
            else
            {
                if (userId > 0)
                {
                    User user = UsersController.GetUser(userId);
                    context.Response.ContentType = "image/jpeg";
                    if (context.Session["UserLogoFile"] != null)
                    {
                        byte[] fileContent = File.ReadAllBytes(context.Server.MapPath("~/tempImages/" + context.Session["UserLogoFile"].ToString()));
                        context.Response.BinaryWrite(fileContent);
                    }
                    else
                    {
                        if (user.UserLogo != null)
                        {
                            context.Response.BinaryWrite(user.UserLogo);
                        }
                        else
                        {
                            context.Response.WriteFile("images/user-unknow-icon-100.jpg");
                        }
                    }
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}